package main.Primavera;

import com.primavera.ServerException;
import com.primavera.integration.client.Session;
import com.primavera.integration.client.bo.BOIterator;
import com.primavera.integration.client.bo.BusinessObjectException;
import com.primavera.integration.client.bo.object.*;
import com.primavera.integration.network.NetworkException;
import main.SQL.MsSQLConnect;
import main.synch.PrimaveraProject;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

/**
 * Created by s_shmakov on 29.12.2014.
 */
public class ProjectConfig {

    private PrimaveraProject primaveraProject;

    private HashMap<String, ConfigNode> configList;
    private boolean good;
    private HashMap<String, ConfigNode> hashActCodeType, hashProjectCode;
    private DefaultComboBoxModel<ConfigNode> actCodeAssTableModel, actStageCodeAssTableModel, actCodeAssNPZTableModel, WDCodeAssTableModel, SectorCodeAssTableModel, projectCodeModel;
    private JComboBox actCodeAssTableText, actStageCodeAssTableText, actCodeAssNPZTableText, WDCodeAssTableText, SectorCodeAssTableText, projectCodeText;


    private Connection connSql;
    private Session curSession;
    private Project curProj;
    private int projId;
    private String dbName;

    public ProjectConfig(PrimaveraProject primaveraProject) {
        configList = new HashMap<>();
        this.primaveraProject = primaveraProject;
        this.curProj = primaveraProject.getCurProject();
        good = false;
    }

    public ProjectConfig(int projectId, String dbName) {

    }

    private Project getPrimaveraProject() {
        BOIterator<Project> boiWBS = null;
        try {
            boiWBS = curSession.getGlobalObjectManager().loadProjects(new String[]
                    {
                            "ObjectId", "Name", "Id", "WBSObjectId"
                    }, "ObjectId = " + projId, null);
            while (boiWBS.hasNext()) {
                curProj = boiWBS.next();
            }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (NetworkException e) {
            e.printStackTrace();
        } catch (BusinessObjectException e) {
            e.printStackTrace();
        }

        return curProj;
    }

    public HashMap<String, ConfigNode> getConfigList() {
        return configList;
    }

    public void addConfigItem(ConfigNode conf) {
        configList.put(conf.getConfigType(), conf);
    }

    public int getConfigId(String configName) {
        int id = configList.get(configName).getConfigId();
        return id;
    }

    //region Вид работ
    private String actCodeAssTable;
    private int actCodeAssTableId;
    //endregion

    //region Стадия
    private String actStageCodeAssTable;
    private int actStageCodeAssTableId;
    //endregion

    //region Вид работ НПЗ
    private String actCodeAssNPZTable;
    private int actCodeAssNPZTableId;
    //endregion

    //region Назначение РД
    private String WDCodeAssTable;
    private int WDCodeAssTableId;
    //endregion

    //region Код работ РД
    private String WDCodeTable;
    private int WDCodeTableId;
    //endregion

    //region Назначения Сектора
    private String SectorCodeAssTable;
    private int SectorCodeAssTableId;
    //endregion

    //region Коды секторов
    private String sectorCodeTable;
    private int sectorCodeTableId;
    //endregion

    public void setConfig() {

        getLists();
        setModel();

        init();

    }

    public void editConfig() {
        curProj = getPrimaveraProject();
        setConfig();

        projectCodeText.setSelectedItem(configList.get("projCode"));
        actCodeAssTableText.setSelectedItem(configList.get("actCodeAssTable"));
        actStageCodeAssTableText.setSelectedItem(configList.get("actStageCodeAssTable"));
        actCodeAssNPZTableText.setSelectedItem(configList.get("actCodeAssNPZTable"));
        WDCodeAssTableText.setSelectedItem(configList.get("WDCodeAssTable"));
        SectorCodeAssTableText.setSelectedItem(configList.get("sectorCodeAssTable"));

//        actCodeAssTableText, actStageCodeAssTableText, actCodeAssNPZTableText, WDCodeAssTableText, SectorCodeAssTableText, projectCodeText
    }

    public void loadConfig(int projectId, String dbName) {
        try {
            connSql = MsSQLConnect.ConnectDB("Factage");
            CallableStatement stmt = connSql.prepareCall("{call getConfig(?, ?)}");
            stmt.setString(1, dbName);
            stmt.setInt(2, projectId);

            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                addConfigItem(new ConfigNode(rs.getString("type"), rs.getString("value"), rs.getInt("value_id")));
            }
            stmt.close();
            rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private void init() {
        final JDialog frame = new JDialog();
        frame.setTitle("Настройки синхронизации проекта");
        int width = 400;
        int height = 300;
        frame.setSize(new Dimension(width, height));
        Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
        frame.setLocation(screensize.width / 2 - width / 2, screensize.height / 2 - height / 2);

        frame.setLayout(new GridBagLayout());
        GridBagConstraints c;

        //region Объявление элементов формы

        JLabel projectCodeLabel = new JLabel("Код проекта");
        JLabel actCodeAssTableLabel = new JLabel("Вид работ");
        JLabel actStageCodeAssTableLabel = new JLabel("Стадия");
        JLabel actCodeAssNPZTableLabel = new JLabel("Вид работ НПЗ");
        JLabel WDCodeAssTableLabel = new JLabel("Назначение РД");
        JLabel WDCodeTableLabel = new JLabel("Код работ РД");
        JLabel SectorCodeAssTableLabel = new JLabel("Назначения сектора");
        JLabel sectorCodeTableLabel = new JLabel("Коды секторов");

        projectCodeText = new JComboBox();
        projectCodeText.setModel(projectCodeModel);
        projectCodeText.setRenderer(new ComboRenderer());
        actCodeAssTableText = new JComboBox();
        actCodeAssTableText.setModel(actCodeAssTableModel);
        actCodeAssTableText.setRenderer(new ComboRenderer());
        actStageCodeAssTableText = new JComboBox();
        actStageCodeAssTableText.setModel(actStageCodeAssTableModel);
        actStageCodeAssTableText.setRenderer(new ComboRenderer());
        actCodeAssNPZTableText = new JComboBox();
        actCodeAssNPZTableText.setModel(actCodeAssNPZTableModel);
        actCodeAssNPZTableText.setRenderer(new ComboRenderer());
        WDCodeAssTableText = new JComboBox();
        WDCodeAssTableText.setModel(WDCodeAssTableModel);
        WDCodeAssTableText.setRenderer(new ComboRenderer());
        JComboBox WDCodeTableText = new JComboBox();
        SectorCodeAssTableText = new JComboBox();
        SectorCodeAssTableText.setModel(SectorCodeAssTableModel);
        SectorCodeAssTableText.setRenderer(new ComboRenderer());
        JComboBox sectorCodeTableText = new JComboBox();

        //endregion

        JButton ok = new JButton("Сохранить");
        ok.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                checkOk();
                frame.setVisible(false);
            }
        });
        JButton cancel = new JButton("Отмена");
        cancel.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                frame.setVisible(false);
            }
        });

        //region Менеджер компановки
        c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 0;
        c.insets = new Insets(20, 20, 5, 5);
        c.anchor = GridBagConstraints.EAST;
        frame.add(projectCodeLabel, c);

        c = new GridBagConstraints();
        c.gridx = 1;
        c.gridy = 0;
        c.weightx = 1;
        c.insets = new Insets(20, 5, 5, 20);
        c.anchor = GridBagConstraints.WEST;
        c.fill = GridBagConstraints.HORIZONTAL;
        frame.add(projectCodeText, c);

        c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 1;
        c.insets = new Insets(10, 20, 5, 5);
        c.anchor = GridBagConstraints.EAST;
        frame.add(actCodeAssTableLabel, c);

        c = new GridBagConstraints();
        c.gridx = 1;
        c.gridy = 1;
        c.weightx = 1;
        c.insets = new Insets(10, 5, 5, 20);
        c.anchor = GridBagConstraints.WEST;
        c.fill = GridBagConstraints.HORIZONTAL;
        frame.add(actCodeAssTableText, c);

        c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 2;
        c.insets = new Insets(10, 20, 5, 5);
        c.anchor = GridBagConstraints.EAST;
        frame.add(actStageCodeAssTableLabel, c);

        c = new GridBagConstraints();
        c.gridx = 1;
        c.gridy = 2;
        c.weightx = 1;
        c.insets = new Insets(10, 5, 5, 20);
        c.anchor = GridBagConstraints.WEST;
        c.fill = GridBagConstraints.HORIZONTAL;
        frame.add(actStageCodeAssTableText, c);

        c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 3;
        c.insets = new Insets(10, 20, 5, 5);
        c.anchor = GridBagConstraints.EAST;
        frame.add(actCodeAssNPZTableLabel, c);

        c = new GridBagConstraints();
        c.gridx = 1;
        c.gridy = 3;
        c.weightx = 1;
        c.insets = new Insets(10, 5, 5, 20);
        c.anchor = GridBagConstraints.WEST;
        c.fill = GridBagConstraints.HORIZONTAL;
        frame.add(actCodeAssNPZTableText, c);

        c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 4;
        c.insets = new Insets(10, 20, 5, 5);
        c.anchor = GridBagConstraints.EAST;
        frame.add(WDCodeAssTableLabel, c);

        c = new GridBagConstraints();
        c.gridx = 1;
        c.gridy = 4;
        c.weightx = 1;
        c.insets = new Insets(10, 5, 5, 20);
        c.anchor = GridBagConstraints.WEST;
        c.fill = GridBagConstraints.HORIZONTAL;
        frame.add(WDCodeAssTableText, c);

//        c = new GridBagConstraints();
//        c.gridx = 0;
//        c.gridy = 4;
//        c.insets = new Insets(10, 20, 5, 5);
//        c.anchor = GridBagConstraints.EAST;
//        frame.add(WDCodeTableLabel, c);
//
//        c = new GridBagConstraints();
//        c.gridx = 1;
//        c.gridy = 4;
//        c.weightx = 1;
//        c.insets = new Insets(10, 5, 5, 20);
//        c.anchor = GridBagConstraints.WEST;
//        c.fill = GridBagConstraints.HORIZONTAL;
//        frame.add(WDCodeTableText, c);

        c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 5;
        c.insets = new Insets(10, 20, 5, 5);
        c.anchor = GridBagConstraints.EAST;
        frame.add(SectorCodeAssTableLabel, c);

        c = new GridBagConstraints();
        c.gridx = 1;
        c.gridy = 5;
        c.weightx = 1;
        c.insets = new Insets(10, 5, 5, 20);
        c.anchor = GridBagConstraints.WEST;
        c.fill = GridBagConstraints.HORIZONTAL;
        frame.add(SectorCodeAssTableText, c);

//        c = new GridBagConstraints();
//        c.gridx = 0;
//        c.gridy = 6;
//        c.insets = new Insets(10, 20, 5, 5);
//        c.anchor = GridBagConstraints.EAST;
//        frame.add(sectorCodeTableLabel, c);
//
//        c = new GridBagConstraints();
//        c.gridx = 1;
//        c.gridy = 6;
//        c.weightx = 1;
//        c.insets = new Insets(10, 5, 5, 20);
//        c.anchor = GridBagConstraints.WEST;
//        c.fill = GridBagConstraints.HORIZONTAL;
//        frame.add(sectorCodeTableText, c);

        c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 7;
        c.insets = new Insets(10, 20, 5, 5);
        c.anchor = GridBagConstraints.EAST;
        frame.add(ok, c);

        c = new GridBagConstraints();
        c.gridx = 1;
        c.gridy = 7;
        c.insets = new Insets(10, 5, 5, 20);
        c.anchor = GridBagConstraints.WEST;
        frame.add(cancel, c);

        //endregion

        frame.setBackground(new java.awt.Color(255, 255, 255));
        frame.setForeground(new java.awt.Color(255, 255, 255));
        frame.setVisible(true);
        frame.setModal(true);
    }

    private void getLists() {
        hashActCodeType = new HashMap<>();
        hashProjectCode = new HashMap<>();
        HashMap<Integer, String> hashAC = new HashMap<>();
        HashMap<Integer, String> hashPC = new HashMap<>();
        int i = 0;

        try {
            BOIterator<ActivityCodeAssignment> listActCodeType = curProj.loadAllActivityCodeAssignments(new String[]{
                    "ActivityCodeTypeName", "ActivityCodeTypeObjectId"}, null, null);
            while (listActCodeType.hasNext()) {
                ActivityCodeAssignment temp = listActCodeType.next();
                hashAC.put(temp.getActivityCodeTypeObjectId().toInteger(), temp.getActivityCodeTypeName());
            }
            BOIterator<ProjectCodeAssignment> boiProjAss = curProj.loadProjectCodeAssignments(new String[]
                    {
                            "ProjectCodeTypeName", "ProjectCodeValue", "ProjectId", "ProjectCodeDescription"
                    }, null, null);
            while (boiProjAss.hasNext()) {
                ProjectCodeAssignment temp = boiProjAss.next();
                hashPC.put(temp.getProjectCodeTypeObjectId().toInteger(), temp.getProjectCodeTypeName());
            }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (NetworkException e) {
            e.printStackTrace();
        } catch (BusinessObjectException e) {
            e.printStackTrace();
        }

        for (Integer key : hashAC.keySet()) {
            hashActCodeType.put(hashAC.get(key), new ConfigNode("actCodeAssTable", hashAC.get(key), key));
            i++;
        }
        i = 0;
        for (Integer key : hashPC.keySet()) {
            hashProjectCode.put(hashPC.get(key), new ConfigNode("projCode", hashPC.get(key), key));
            i++;
        }

    }

    private void setModel() {
        actCodeAssTableModel = new DefaultComboBoxModel<>();
        actStageCodeAssTableModel = new DefaultComboBoxModel<>();
        actCodeAssNPZTableModel = new DefaultComboBoxModel<>();
        WDCodeAssTableModel = new DefaultComboBoxModel<>();
        SectorCodeAssTableModel = new DefaultComboBoxModel<>();
        ArrayList<String> sortHACT = new ArrayList<>(hashActCodeType.keySet());
        Collections.sort(sortHACT);
        for (String key : sortHACT) {
            ConfigNode cn = hashActCodeType.get(key);
            actCodeAssTableModel.addElement(cn);
            cn.setConfigType("actStageCodeAssTable");
            actStageCodeAssTableModel.addElement(cn);
            cn.setConfigType("actCodeAssNPZTable");
            actCodeAssNPZTableModel.addElement(cn);
            cn.setConfigType("WDCodeAssTable");
            WDCodeAssTableModel.addElement(cn);
            cn.setConfigType("sectorCodeAssTable");
            SectorCodeAssTableModel.addElement(cn);
        }
//        for (ConfigNode cn : hashActCodeType.values()) {
//            actCodeAssTableModel.addElement(cn);
//            cn.setConfigType("actStageCodeAssTable");
//            actStageCodeAssTableModel.addElement(cn);
//            cn.setConfigType("actCodeAssNPZTable");
//            actCodeAssNPZTableModel.addElement(cn);
//            cn.setConfigType("WDCodeAssTable");
//            WDCodeAssTableModel.addElement(cn);
//            cn.setConfigType("sectorCodeAssTable");
//            SectorCodeAssTableModel.addElement(cn);
//        }

        projectCodeModel = new DefaultComboBoxModel<>();
        for (ConfigNode pc : hashProjectCode.values()) {
            projectCodeModel.addElement(pc);
        }
    }

    private void checkOk() {
        ConfigNode tempprojectCodeText = (ConfigNode) projectCodeText.getSelectedItem();
        configList.put("projCode", tempprojectCodeText);
        ConfigNode tempactCodeAssTableText = (ConfigNode) actCodeAssTableText.getSelectedItem();
        configList.put("actCodeAssTable", tempactCodeAssTableText);
        ConfigNode tempactStageCodeAssTableText = (ConfigNode) actStageCodeAssTableText.getSelectedItem();
        configList.put("actStageCodeAssTable", tempactStageCodeAssTableText);
        ConfigNode tempactCodeAssNPZTableText = (ConfigNode) actCodeAssNPZTableText.getSelectedItem();
        configList.put("actCodeAssNPZTable", tempactCodeAssNPZTableText);
        ConfigNode tempWDCodeAssTableText = (ConfigNode) WDCodeAssTableText.getSelectedItem();
        configList.put("WDCodeAssTable", tempWDCodeAssTableText);
        ConfigNode tempsectorCodeAssTableText = (ConfigNode) SectorCodeAssTableText.getSelectedItem();
        configList.put("sectorCodeAssTable", tempsectorCodeAssTableText);

        saveConfig();

//        primaveraProject.synchProject();
    }

    private void saveConfig() {
        for (String cn : configList.keySet()) {
            primaveraProject.saveConfig(cn, configList.get(cn).getConfigValue(), configList.get(cn).getConfigId());
        }
    }

    public String getActCodeAssTable() {
        return actCodeAssTable;
    }

    public void setActCodeAssTable(String actCodeAssTable) {
        this.actCodeAssTable = actCodeAssTable;
    }

    public int getActCodeAssTableId() {
        return actCodeAssTableId;
    }

    public void setActCodeAssTableId(int actCodeAssTableId) {
        this.actCodeAssTableId = actCodeAssTableId;
    }

    public String getActStageCodeAssTable() {
        return actStageCodeAssTable;
    }

    public void setActStageCodeAssTable(String actStageCodeAssTable) {
        this.actStageCodeAssTable = actStageCodeAssTable;
    }

    public int getActStageCodeAssTableId() {
        return actStageCodeAssTableId;
    }

    public void setActStageCodeAssTableId(int actStageCodeAssTableId) {
        this.actStageCodeAssTableId = actStageCodeAssTableId;
    }

    public String getActCodeAssNPZTable() {
        return actCodeAssNPZTable;
    }

    public void setActCodeAssNPZTable(String actCodeAssNPZTable) {
        this.actCodeAssNPZTable = actCodeAssNPZTable;
    }

    public int getActCodeAssNPZTableId() {
        return actCodeAssNPZTableId;
    }

    public void setActCodeAssNPZTableId(int actCodeAssNPZTableId) {
        this.actCodeAssNPZTableId = actCodeAssNPZTableId;
    }

    public String getWDCodeAssTable() {
        return WDCodeAssTable;
    }

    public void setWDCodeAssTable(String WDCodeAssTable) {
        this.WDCodeAssTable = WDCodeAssTable;
    }

    public int getWDCodeAssTableId() {
        return WDCodeAssTableId;
    }

    public void setWDCodeAssTableId(int WDCodeAssTableId) {
        this.WDCodeAssTableId = WDCodeAssTableId;
    }

    public String getWDCodeTable() {
        return WDCodeTable;
    }

    public void setWDCodeTable(String WDCodeTable) {
        this.WDCodeTable = WDCodeTable;
    }

    public int getWDCodeTableId() {
        return WDCodeTableId;
    }

    public void setWDCodeTableId(int WDCodeTableId) {
        this.WDCodeTableId = WDCodeTableId;
    }

    public String getSectorCodeAssTable() {
        return SectorCodeAssTable;
    }

    public void setSectorCodeAssTable(String sectorCodeAssTable) {
        SectorCodeAssTable = sectorCodeAssTable;
    }

    public int getSectorCodeAssTableId() {
        return SectorCodeAssTableId;
    }

    public void setSectorCodeAssTableId(int sectorCodeAssTableId) {
        SectorCodeAssTableId = sectorCodeAssTableId;
    }

    public String getSectorCodeTable() {
        return sectorCodeTable;
    }

    public void setSectorCodeTable(String sectorCodeTable) {
        this.sectorCodeTable = sectorCodeTable;
    }

    public int getSectorCodeTableId() {
        return sectorCodeTableId;
    }

    public void setSectorCodeTableId(int sectorCodeTableId) {
        this.sectorCodeTableId = sectorCodeTableId;
    }


}




